package cn.antho.pet.service.impl;

import cn.antho.basic.config.BussinessException;
import cn.antho.basic.domain.Point;
import cn.antho.basic.util.*;
import cn.antho.order.domain.OrderPetAcquisition;
import cn.antho.order.service.IOrderPetAcquisitionService;
import cn.antho.org.domain.Employee;
import cn.antho.org.domain.Shop;
import cn.antho.org.mapper.EmployeeMapper;
import cn.antho.org.service.IShopService;
import cn.antho.pet.domain.SearchMasterMsg;
import cn.antho.pet.domain.SearchMasterMsgAuditLog;
import cn.antho.pet.dto.AcceptDto;
import cn.antho.pet.mapper.SearchMasterMsgMapper;
import cn.antho.pet.query.SearchMasterMsgQuery;
import cn.antho.pet.service.ISearchMasterMsgService;
import cn.antho.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author antho
 * @since 2022-11-01
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IShopService shopService;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private IOrderPetAcquisitionService orderPetAcquisitionService;

    /**
     * 发布寻主消息
     * @param searchMasterMsg
     * @return
     */
    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg) {
        // 直接保存寻主消息 默认状态 待审核
        searchMasterMsgMapper.add(searchMasterMsg);
        // 参数为空校验
        paramCheck(searchMasterMsg);
        // 百度AI审核 如果有企业定制审核还需要使用定制审核
        BaiduAiCheck(searchMasterMsg);

        // 成功：根据用户填写的地址找方圆50km的最近的店铺 设置shopId 没找到就不管
        Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
        List<Shop> shops = shopService.findAll();
        Shop shop = DistanceUtil.getNearestShop(point, shops);
        if (shop != null) {
            searchMasterMsg.setShopId(shop.getId());
        }
        // 修改状态为审核通过
        searchMasterMsg.setState(1);
        // 调用数据库进行修改
        searchMasterMsgMapper.update(searchMasterMsg);

        return AjaxResult.me().success();
    }

    @Override
    public PageList<SearchMasterMsg> selectSearchMasterMsgByParam(SearchMasterMsgQuery query) {
        // 总条数
        Integer totals = searchMasterMsgMapper.selectSearchMasterMsgByParamCount(query);
        if (null == totals || 0 == totals) {
            return new PageList<>(0, new ArrayList<>());
        }
        // 数据
        List<SearchMasterMsg> list = searchMasterMsgMapper.selectSearchMasterMsgByParam(query);
        return new PageList<>(totals, list);
    }

    @Override
    public void accept(AcceptDto dto) {
        // 根据id查询到寻主消息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(dto.getMsgId());
        // 校验寻主消息是否为空
        if (null == searchMasterMsg) {
            throw new BussinessException("寻主消息为空！");
        }
        // 解决线程安全问题
        synchronized (searchMasterMsg.getId()) {
            // 判断员工是否为空
            Employee employee = employeeMapper.findById(dto.getHandler());
            if (null == employee) {
                throw new BussinessException("员工为空！请校验！");
            }
            // 判断寻主消息状态 校验寻主消息中店铺id与员工shopId
            if (1 == searchMasterMsg.getState() && searchMasterMsg.getShopId().equals(employee.getShopId())) {
                // 修改寻主消息状态
                searchMasterMsg.setState(2);
                searchMasterMsgMapper.update(searchMasterMsg);
            }
            // 生成订单
            initOrder(dto, searchMasterMsg, employee);
        }
    }

    @Override
    public void reject(Long msgId, Employee emp) {
        // 根据msgId查询到寻主消息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(msgId);
        // 校验寻主消息是否为空
        if (null == searchMasterMsg) {
            throw new BussinessException("寻主消息为空！");
        }
        // 拒单 即是置空shopId 放入寻主池
        searchMasterMsg.setShopId(null);
        searchMasterMsgMapper.update(searchMasterMsg);
        // 保存拒单日志

    }

    /**
     * 生成订单方法
     * @param dto
     * @param searchMasterMsg
     * @param employee
     */
    private void initOrder(AcceptDto dto, SearchMasterMsg searchMasterMsg, Employee employee) {
        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
        orderPetAcquisition.setOrderSn(CodeGenerateUtils.generateOrderSn(dto.getHandler()));
        orderPetAcquisition.setDigest(dto.getNote());
        orderPetAcquisition.setLastcomfirmtime(new Date(System.currentTimeMillis() + 3 * 24 * 60 * 60 * 1000));
        orderPetAcquisition.setState(0);
        orderPetAcquisition.setPrice(new BigDecimal(searchMasterMsg.getPrice()));
        orderPetAcquisition.setUserId(searchMasterMsg.getUserId());
        orderPetAcquisition.setShopId(employee.getShopId());
        orderPetAcquisition.setAddress(searchMasterMsg.getAddress());
        orderPetAcquisition.setEmpId(employee.getId());
        orderPetAcquisition.setSearchMasterMsgId(searchMasterMsg.getId());
        orderPetAcquisitionService.add(orderPetAcquisition);
    }

    private void BaiduAiCheck(SearchMasterMsg searchMasterMsg) {
        StringBuilder sb = new StringBuilder();
        sb.append(searchMasterMsg.getName())
                .append(searchMasterMsg.getAddress())
                .append(searchMasterMsg.getNote());
        if (!BaiduAuditUtils.TextCensor(sb.toString())) {
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLog.setNote("信息设计违规，审核失败，请在个人中心修改！");
            throw new BussinessException("信息设计违规，审核失败，请在个人中心修改！");
        }
    }

    private void paramCheck(SearchMasterMsg searchMasterMsg) {
        if (StringUtils.isEmpty(searchMasterMsg.getName()) || StringUtils.isEmpty(searchMasterMsg.getAddress())) {
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLog.setNote("参数为空，审核失败，请在个人中心修改！");
            throw new BussinessException("参数为空，审核失败，请在个人中心修改！");
        }

    }
}
